<template>
  <div>
    <BasicModal
      v-model:visible="showContract"
      :title="announcementId ? '修改资料' : '新增资料'"
      @ok="onSubmit"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <FormItem label="名称" name="name">
          <Input v-model:value="formState.name" placeholder="请输入资料名称" />
        </FormItem>
        <FormItem label="备注" name="comment">
          <a-textarea v-model:value="formState.comment" placeholder="请输入备注" />
        </FormItem>
        <FormItem label="资料附件" name="urlArr" v-if="!announcementId">
          <Upload
            :multiple="true"
            :before-upload="beforeUpload"
            :file-list="formState.urlArr"
            :remove="removeFile"
            @change="handleChange"
          >
            <a-button @click="Detectmultiplefiles">
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </Upload>
          <Progress
            v-if="percentNum != 0 && percentNum != 100"
            :percent="percentNum"
            status="active"
          />
        </FormItem>
      </Form>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, getCurrentInstance } from 'vue';
  import { Modal, Form, Input, FormItem, message, Upload, Progress } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { modifyDataCenter, AddDataCenter } from '/@/api/announcements';
  import { fileUploadApi, fileViewApi } from '/@/api/projectManagement';
  import { BasicModal } from '/@/components/Modal';
  import axios from 'axios';
  const instance = getCurrentInstance();

  const { createMessage } = useMessage();
  const emit = defineEmits(['reload']);
  const formRef = ref();
  const formState = reactive({
    name: '',
    urlArr: [],
    urls: [],
    comment: '',
  });
  let validatePass2 = () => {
    if (percentNum.value != 0 && percentNum.value != 100) {
      return Promise.resolve();
    } else {
      if (formState.urlArr.length <= 0) {
        return Promise.reject('请上传附件');
      } else {
        return Promise.resolve();
      }
    }
  };
  const removeFile = (e) => {
    const index = formState.urlArr.findIndex(item => item.uid === e.uid);
    if (index !== -1) {
      formState.urlArr.splice(index, 1);
      formState.urls.splice(index, 1);
    }
  };
  const Detectmultiplefiles = () => {
    if (formState.urlArr.length > 0) {
      // return message.warn('已经上传了一个文件，再次上传会覆盖之前的文件');
    }
  };
  const percentNum = ref(0);
  const beforeUpload = (file) => {
    // let formData = new FormData();
    // formData.append('file', file);
    // fileUploadApi(formData).then((res) => {
    //   // formState.urls = [file];
    //   formState.urls.push(res);
    //   formState.urlArr.push(file);
    //   formRef.value.clearValidate('urlArr');
    // });

    // return false;
    if (percentNum.value != 0 && percentNum.value != 100) {
      return message.warn('已有正在上传的文件了，请稍后');
    }
    let formData = new FormData();
    formData.append('file', file);
    // formState.urlArr.push(file);
    formState.urlArr = [file];
    percentNum.value = 0;
    axios
      .post('https://admin-api.gongcheng1949.com/v1/file/upload', formData, {
        onUploadProgress: function (progressEvent) {
          let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          if (percentCompleted == 100) {
            percentNum.value = 99;
          } else {
            percentNum.value = percentCompleted;
          }
        },
      })
      .then((res) => {
        // 处理服务器响应
        //formState.urls.push(res.data.data); // 假设服务器返回的URL在data.url中
        if (res.data.code == '0') {
          formState.urls = [res.data.data];
          percentNum.value = 100;
          formRef.value.clearValidate('urlArr');
        } else {
          message.error(res.data.message);
          percentNum.value = 0;
          formState.urlArr = [];
          formState.urls = [];
        }
      })
      .catch((error) => {
        message.error('上传失败换个文件试试吧');
        percentNum.value = 0;
        formState.urlArr = [];
        formState.urls = [];
        console.error('Upload Error:', error);
      });

    return false;
  };
  const handleChange = (info) => {
    if (info.file.status == 'removed') {
      formState.urls = [];
    }
  };

  const rules = {
    name: [{ required: true, message: '请输入资料名称' }],
    urlArr: [{ required: true, validator: validatePass2, trigger: 'change' }],
    comment: [{ required: true, message: '请输入备注内容' }],
  };

  const showContract = ref(false);
  const announcementId = ref(null);
  const init = (data) => {
    resetForm();
    announcementId.value = null;
    if (data?.id) {
      announcementId.value = data.id;
      formState.name = data.name;
      formState.comment = data.comment;
      formState.urls = data.urlArr;
      // for (let i in formState.urls) {
      //   fileViewApi(formState.urls[i]).then((res) => {
      //     let nameExtension = formState.urls[i].split('.')[1];
      //     let file = new File([res], `${data.name}${Number(i) + 1}.${nameExtension}`, { types: nameExtension }); // 创建一个File对象
      //     file.uid = 'v-' + Date.now();
      //     formState.urlArr.push(file);
      //   });
      // }
    }
    showContract.value = true;
  };
  const onSubmit = () => {
    if (percentNum.value != 0 && percentNum.value != 100) {
      return message.warn('请等待文件上传成功后再点击确认');
    }
    formRef.value
      .validate()
      .then(() => {
        if (announcementId.value) {
          const { urlArr, ...restFormState } = formState;
          modifyDataCenter({
            id: announcementId.value,
            ...restFormState,
          }).then((res) => {
            if (res != false) {
              message.success('修改成功');
              showContract.value = false;
              resetForm();
              emit('reload');
            }
          });
        } else {
          const { urlArr, ...restFormState } = formState;
          AddDataCenter(restFormState).then((res) => {
            console.log(res, 'res');
            if (res != false) {
              message.success('新增成功');
              showContract.value = false;
              resetForm();
              emit('reload');
            }
          });
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.comment = '';
    formState.name = '';
    formState.urlArr = [];
    formState.urls = [];
  };

  defineExpose({
    init,
  });
</script>
<style>
  .form_box {
    padding: 20px;
  }
</style>
